﻿using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Collections.Generic;
using System.Web.Script.Serialization;
using Newtonsoft.Json.Linq;

namespace WeChat.Common
{
    /// <summary>
    /// $codebehindclassname$ 的摘要说明
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class GetMedia1 : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string accesstoken = GetAccess_token.getAccesstoken();
            string url = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=" + accesstoken;
            /*
             * 发送post请求传送的json
             * type返回素材类型:图片（image）、视频（video）、语音 （voice）、图文（news）
             * offset从第几个元素开始（一般为0）
             * count一共返回几个元素（取值1-20）
             */
            string type = "image";
            string jsondata = "{\"type\":\""+ type +"\",\"offset\":\"0\",\"count\":\"10\"}";

            List<Medias> list = new List<Medias>();//创建list对象保存素材title和media_id

            //Dictionary<string, object> dc = new GetReturnJson().postReturnJson(url, jsondata);
            string jsons = new GetReturnJson().postReturnJson(url, jsondata);
            var js = new JavaScriptSerializer();
            var dc = js.Deserialize<Dictionary<string, object>>(jsons);
            if (dc.ContainsKey("errcode"))
            {
                ApplicationLog.Write("获取素材列表失败，errcode:" + dc["errcode"]);
            }

            else if (type.Equals("news"))//获取图文素材
            {
                JObject jo = JObject.Parse(jsons);
                JArray ja = JArray.Parse(jo["item"].ToString());
                foreach (JToken jt in ja)
                {
                    string media_ids = jt["media_id"].ToString();
                    string titles = jt["content"]["news_item"][0]["title"].ToString();
                    ApplicationLog.Write("图文素材title:" + titles + ";media_id:" + media_ids);

                    Medias md = new Medias() { title = titles, media_id = media_ids };
                    list.Add(md);
                }
            }
            else//获取图片(image)、视频(video)、语音(voice)素材
            {
                JObject jo = JObject.Parse(jsons);
                JArray ja = JArray.Parse(jo["item"].ToString());
                foreach (JToken jt in ja)
                {
                    string media_ids = jt["media_id"].ToString();
                    string name = jt["name"].ToString();
                    ApplicationLog.Write("非图文素材name:" + name + ";media_id:" + media_ids);

                    Medias md = new Medias() { title = name, media_id = media_ids };
                    list.Add(md);
                }
            }
            ApplicationLog.Write(list.ToString());
            //{
                //JObject jo = JObject.Parse(jsons);
                //JArray ja = JArray.Parse(jo["item"].ToString());

                //Dictionary<string, string> dc = new Dictionary<string, string>();
                //int key = 0;
                
                //foreach (JToken jt in ja)
                //{
                //    string media_id = jt["media_id"].ToString();
                //    string title = jt["content"]["news_item"][0]["title"].ToString();

                //    Medias md = new Medias() { title,media_id};
                //    dc.Add(key,md);
                //    key++;
                //    ApplicationLog.Write("素材title:" + title + ";media_id:" + media_id);
                //}
                ////JArray jy = JArray.Parse(ja[0]["content"]["news_item"].ToString());
                ////string title2 = jy[0]["title"].ToString();
                ////ApplicationLog.Write("素材title2" + title2);
            //}
        }
        

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
    //新建media类保存素材title和media_id，存入list
    public class Medias
    {
        public string title { set; get; }
        public string media_id { set; get; }
    }
}
